package com.zyt.servlet.bookhandler;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zyt.model.Book;
import com.zyt.util.MMLog;

public class BookListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BookListServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		List<Book> books = new ArrayList<Book>();

		// 数据库连接处理
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/my-web-db?" + "useUnicode=true&characterEncoding=UTF8";
		String user = "zyt";
		String password = "1234";
		try {
			Class.forName("com.mysql.jdbc.Driver");

			conn = DriverManager.getConnection(url, user, password);
			Statement stmt = conn.createStatement();
			String sql = "CREATE TABLE IF NOT EXISTS book(id INTEGER, name VARCHAR(20), author VARCHAR(20), price INTEGER, bookCount INTEGER, PRIMARY KEY (id));";
			int result = stmt.executeUpdate(sql);
			if (result != -1) {
				// create table success
				MMLog.log("create table success");

				// 添加数据
				sql = "SELECT * from book";
				Statement querySt = conn.createStatement();

				ResultSet resultSet = querySt.executeQuery(sql);
				while (resultSet.next()) {
					Book book = new Book();
					book.setId(resultSet.getInt("id"));
					book.setName(resultSet.getString("name"));
					book.setAuthor(resultSet.getString("author"));
					book.setPrice(resultSet.getDouble("price"));
					book.setBookCount(resultSet.getInt("bookCount"));
					books.add(book);
				}

				querySt.close();
				conn.close();
			}

		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("添加失败");
			e.printStackTrace();
		}
		
		// 保存数据到request容器中
		request.setAttribute("books", books);
		
		// dispatch到View页面
		request.getRequestDispatcher("/book_list.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
